package com.axc.gallery2.net.activity;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore.Images.Media;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;

import com.axc.gallery2.R;
import com.axc.gallery2.dbhelper.AlbumInfo;
import com.axc.gallery2.dbhelper.ImageInfo;
import com.axc.gallery2.net.ApiInvoker;
import com.axc.gallery2.net.AsyncDownPhotos;
import com.axc.gallery2.net.CheckNetworkState;
import com.axc.gallery2.net.UploadAdapterHelper;
import com.axc.gallery2.view.UploadPhotosAdapter;
import com.axc.gallery2.view.UploadPhotosAdapter.OnUploadListener;
import com.renren.api.connect.android.Renren;
import com.renren.api.connect.android.common.AbstractRequestListener;
import com.renren.api.connect.android.exception.RenrenError;
import com.renren.api.connect.android.photos.PhotoUploadRequestParam;
import com.renren.api.connect.android.photos.PhotoUploadResponseBean;

public class UploadPhotosActivity extends Activity {


	CheckNetworkState checkNetworkState;
	private Renren renren;
	UploadPhotosAdapter adapter;
	// 主题应用
	public static UploadPhotosActivity Talbum;
	public int theme = -1;
	/**
	 * 标识数据状态的消息值，依次为发送成功，出现异常，出现严重错误
	 */
	private final static int DATA_COMPLETE = 0xffff;
	private final static int DATA_ERROR = 0xfffe;
	private final static int DATA_FAULT = 0xfffd;

	/**
	 * Bundle参数设置中的字符串标识符
	 */
	private final  String BEAN_LABEL = "bean";
	private final  String ERROR_LABEL = "error";

	/**
	 * 上传完成索引
	 */
	private final String DATA_COMPLETE_POSITION="DATA_COMPLETE_POSITION";
	private List<ImageInfo> pathList1;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		// 主题
		Talbum = this;
		theme = getSharedPreferences("cons", MODE_PRIVATE).getInt("theme",
				android.R.style.Theme);
		setTheme(theme);
		super.onCreate(savedInstanceState);
		// 设置不显示标题栏
		requestWindowFeature(Window.FEATURE_NO_TITLE);

		// 初始化人人网络相册
		renren = new Renren(NetAlbumsActivity.getApiKey(), NetAlbumsActivity.getSecretKey(), NetAlbumsActivity.getAppId(), this);

//		UploadAdapterHelper.setAdpter(new UploadPhotosAdapter(this, new ArrayList<String>()), this);
		
		ApiInvoker.init(renren);
		checkNetworkState = new CheckNetworkState(this);
		
		int state = checkNetworkState.NetworkState();
		System.out.println("检测网络连接: " + state);
		switch (state) {
		case 0:
			// 2G、3G网络正常

		case 1:
			// wifi网络正常
			Bundle bundle = getIntent().getExtras();
			System.out.println("bundle:"+bundle==null);
			for (String s : UploadAdapterHelper.getAdapter(this).getList()) {
				System.out.println("UploadAdapterHelper:"+s);
			}
			if (bundle != null) {
				pathList1 = ((AlbumInfo) bundle
						.getSerializable(AlbumInfo.SERALIZABLEKEY))
						.getAlbumItems();
				List<String> pathList =new ArrayList<String>();
				for (ImageInfo string : pathList1) {
					//图片编号
//					String image_id=string.image_id;
					String path = "";
//					String[] projection = { Media._ID, Media.DATA }; 
//					if(image_id!=null&&!image_id.equals("")){
//						Cursor cursor = getContentResolver().query(Media.EXTERNAL_CONTENT_URI, projection,  
//								Media._ID + "=" + image_id, null, null);  
//						if (cursor != null) {  
//							cursor.moveToFirst();  
//							path = cursor.getString(cursor.getColumnIndex(Media.DATA));  
//							cursor.close();
//						}
//					}else {
//						path=string.image_path;
//					}
					path=string.image_path;
					pathList.add(path);
				}
				
				//获取适配器
				adapter =  UploadAdapterHelper.getAdapter(this);
				adapter.addItems(pathList);
				UploadAdapterHelper.setAdpter(adapter, this);

			} else {
				adapter = UploadAdapterHelper.getAdapter(this);
				if (adapter == null) {
					adapter = new UploadPhotosAdapter(this,
							new ArrayList<String>());
				}
			}
			LinearLayout line = new LinearLayout(this);
			line.setOrientation(LinearLayout.VERTICAL);
			//			RootMenu rootmenu = new RootMenu(this);
			//			rootmenu.initView();
			//			try {
			//				rootmenu.iniOnClickListener();
			//			} catch (ClassNotFoundException e) {
			//				e.printStackTrace();
			//			}
			//			line.addView(rootmenu);
	
			//操作栏
			LayoutInflater inflater=(LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			inflater.inflate(R.layout.upload_head, line);
			
			//上传列表
			ListView listView = new ListView(this);
			listView.setBackgroundColor(Color.TRANSPARENT);
			adapter.setOnUploadListener(onUploadListener);
			listView.setAdapter(adapter);
			line.addView(listView);
			setContentView(line);
			//返回
			line.findViewById(R.id.upload_back).setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					finish();
					
				}
			});
			//清除列表
			line.findViewById(R.id.upload_clear).setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					UploadAdapterHelper.setAdpter(new UploadPhotosAdapter(UploadPhotosActivity.this, new ArrayList<String>()), UploadPhotosActivity.this);				
					adapter.getList().clear();
					adapter.getStatelList().clear();
					adapter.notifyDataSetChanged();
					Toast.makeText(getBaseContext(), "清除成功！", Toast.LENGTH_LONG).show();
				}
			});
			break;
		case -1:
			checkNetworkState.setNetworkTips();
			break;
		default:
			return;
		}

	}

	/**
	 * 回发处理器
	 */
	Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case DATA_COMPLETE:
				int position =msg.getData().getInt(DATA_COMPLETE_POSITION,-1);
				if(position!=-1){
					//刷新界面
					adapter.SetState(position, 1);
				}
				return;

			default:

				return;
			}
		}

	};

	//上传
	private UploadPhotosAdapter.OnUploadListener onUploadListener =new OnUploadListener() {

		@Override
		public void onUplaod(View view, final int position) {
			//已完成
			if(((Button)view).getText().equals("移除")||((Button)view).getText().equals("取消")){
				//移除列表
				adapter.getList().remove(position);
				adapter.getStatelList().remove(position);
				adapter.notifyDataSetChanged();
				UploadAdapterHelper.setAdpter(adapter, getBaseContext());
				return;
			}
			//未完成
			int state = checkNetworkState.NetworkState();
			if (state == -1)
				checkNetworkState.setNetworkTips();
			else {
				//获取图片真实路径
				ImageInfo string=pathList1.get(position);
				String image_id=string.image_id;
				String path = "";
				String[] projection = { Media._ID, Media.DATA }; 
				if(image_id!=null&&!image_id.equals("")){
					Cursor cursor = getContentResolver().query(Media.EXTERNAL_CONTENT_URI, projection,  
							Media._ID + "=" + image_id, null, null);  
					if (cursor != null) {  
						cursor.moveToFirst();  
						path = cursor.getString(cursor.getColumnIndex(Media.DATA));  
						cursor.close();
					}
				}else {
					path=string.image_path;
				}
				//设置上传状态
				adapter.SetState(position, 2);
				final PhotoUploadRequestParam photoParam = new PhotoUploadRequestParam(
						new File(path));
				// 调用SDK异步上传照片的接口

				new AsyncDownPhotos(renren, UploadPhotosActivity.this)
				.publishPhoto(
						photoParam,
						new AbstractRequestListener<PhotoUploadResponseBean>() {
							@Override
							public void onRenrenError(
									RenrenError renrenError) {
								if (renrenError != null) {
									Message message = new Message();
									Bundle bundle = new Bundle();
									bundle.putString(ERROR_LABEL,
											renrenError.getMessage());
									message.what = DATA_ERROR;
									message.setData(bundle);
									handler.sendMessage(message);
								}
							}

							@Override
							public void onFault(Throwable fault) {
								if (fault != null) {
									Message message = new Message();
									Bundle bundle = new Bundle();
									bundle.putString(ERROR_LABEL, fault
											.getMessage());
									message.what = DATA_FAULT;
									message.setData(bundle);
									handler.sendMessage(message);
								}
							}

							@Override
							public void onComplete(
									PhotoUploadResponseBean bean) {
								if (bean != null) {
									Message message = new Message();
									Bundle bundle = new Bundle();
									bundle.putParcelable(BEAN_LABEL,
											bean);
									bundle.putInt(DATA_COMPLETE_POSITION, position);
									message.what = DATA_COMPLETE;
									message.setData(bundle);
									handler.sendMessage(message);
								}
							}
						});
				}
		}
	};




}
